package workexp.zookeeper;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.RetryNTimes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ZkClientFactory implements PooledObjectFactory<CuratorFramework> {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	private static final ZooKeeperUrlService service= new ZooKeeperUrlServiceImpl(); 

	@Override
	public PooledObject<CuratorFramework> makeObject() throws Exception {
		String zkUrl = service.getUrl();
		if(StringUtils.isBlank(zkUrl)) {
			logger.error("please check config for zklock!");
		}
    	
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString(zkUrl)
				.retryPolicy(new RetryNTimes(5, 1000))
				.connectionTimeoutMs(5000)		
				.build();
		
		client.start();
		
		logger.info("创建CuratorFramework对象成功!");
        return new DefaultPooledObject<CuratorFramework>(client);  
	}

	@Override
	public void destroyObject(PooledObject<CuratorFramework> p) throws Exception {
		CuratorFramework c = p.getObject();
		if(c!=null && c.getState()==CuratorFrameworkState.STARTED){
			c.close();
		}
	}

	@Override
	public boolean validateObject(PooledObject<CuratorFramework> p) {
		CuratorFramework c = p.getObject();
		if (c != null && CuratorFrameworkState.STARTED == c.getState()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void activateObject(PooledObject<CuratorFramework> p) throws Exception {
		CuratorFramework c = p.getObject();
		if (c != null && CuratorFrameworkState.STARTED != c.getState()) {
			c.start();
		}
	}

	@Override
	public void passivateObject(PooledObject<CuratorFramework> p) throws Exception {}
}
